import WxRequest from '../plugins/wx-request/lib/index'
class Service extends WxRequest {
  constructor(options) {
    super(options)
    // 在此也可注入拦截器
    this.interceptors.use({
      request(request) {
        // loading
        wx.showLoading({
          title: '加载中',
          mask: true
        })
        request.header = request.header || {}
        request.header['content-type'] =
          'application/x-www-form-urlencoded;charset=utf-8'
        request.header.ukey = wx.getStorageSync('utoken')
        request.header.sign = '27c5tv6f8w3whebdf73'
        // if (request.url.indexOf('/api') !== -1 && wx.getStorageSync('token')) {
        //   request.header.Authorization = 'Bearer ' + wx.getStorageSync('token')
        // }
        return request
      },
      // 请求失败
      requestError(requestError) {
        wx.hideLoading()
        return Promise.reject(requestError)
      },
      response(response) {
        // loading
        wx.hideLoading()
        const res = response.data
        if (res.status == 200) {
          return res
        } else if (res.status === 401) {
          wx.removeStorageSync('utoken')
          // wx.navigateTo({
          //   url: '/pages/login/index'
          // })
          return Promise.reject()
        } else {
          // 返回错误数据
          if (res.info !== '') {
            wx.showToast({ title: res.info, icon: 'none' })
          }
          return Promise.reject(res)
        }
      },
      // 响应失败
      responseError(responseError) {
        // 响应错误处理
        wx.hideLoading()
        wx.showToast({ title: '喔噢,网络好像出现问题了~', icon: 'none' })
        return Promise.reject(responseError)
      }
    })
  }
}
export { Service }
